package com.yjz.jvm.ThreadLocal;

import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author :yuanJinZhong
 * @description:
 * @date :2018/12/5-21:56
 */
@Slf4j
public class LearnThreadLocal {
  /**
   * static 与否 没有太大的影响（一个类属性 和多个实例属性的区别），毕竟研究对象是thread类
   */
  private static final ThreadLocal<Integer> local = ThreadLocal.withInitial(() -> 2);
  /**
   * static 与否 没有太大的影响（一个类属性 和多个实例属性的区别），毕竟研究对象是thread类
   */
  public static final Lock lock = new ReentrantLock();

  public LearnThreadLocal() {
    local.set(1);
  }

  public static void main(String[] args) throws InterruptedException {
    LearnThreadLocal learnThreadLocal = new LearnThreadLocal();
    log.info("主线程里面：{}", learnThreadLocal.local.get());
    log.info("程序进来了");
    Thread th1 = new Thread(() -> {
      lock.lock();
      try {
        Thread.sleep(2000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      local.set(4);
      log.info("{}", local.get());
      //local.remove();
      lock.unlock();
    }, "线程1");
    Thread th2 = new Thread(() -> {
      try {
        if (lock.tryLock(4, TimeUnit.SECONDS)) {
          log.info("线程2获取到锁");
          lock.unlock();
        } else {
          log.info("线程2 没获取到锁");
        }
        log.info("{}", local.get());
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }, "线程2");
    th1.start();
    th2.start();
    Thread.sleep(10000);

  }
}
